package com.example.flight.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;


public class JwtUtils {
    //7天过期
    private static final long expire = 604800;
    //32位秘钥
    private static final String secret =
            "ABC123456789abc123456789abc123456789abc123456789abc123456789abc123456789ABC123456789ABC123456789ABC123456789";

    //生成token
    public static String generateToken(String  status,String id){
        Date now = new Date();
        Date expiration = new Date(now.getTime() + 1000 * expire);




        return Jwts.builder()
                .claim("id",id)
                .claim("status",status)
                .setHeaderParam("type","JWT")
                .setSubject("exampleFightServe")
                .setIssuedAt(now)
                .setExpiration(expiration)
                .setAudience(id)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    //解析token
    public static Claims getClaimsByToken(String token) throws JwtException {


        Claims body = null;
        try {
            body = Jwts.parserBuilder()
                    .setSigningKey(secret)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new JwtException(token);
        }
        return body;
    }
}


